package utils

import (
	"bytes"
)

//标识该buf在有数据写入时会通知下游，下游传入一个chan bool，当有数据时就会通知
type BufCanBeNotified interface {
	Subscribe(c chan bool)
}

type BufWithNotify struct {
	buf       bytes.Buffer
	notifiers []chan bool
}

func (b *BufWithNotify) Subscribe(c chan bool) {
	b.notifiers = append(b.notifiers, c)
}

func (b *BufWithNotify) Write(p []byte) (n int, err error) {
	for _, c := range b.notifiers {
		if len(c) < cap(c) {
			c <- true
		}
	}
	return b.buf.Write(p)
}

func (b *BufWithNotify) Read(p []byte) (n int, err error) {
	return b.buf.Read(p)
}
